package com.pig4cloud.commcon.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Component
@Slf4j
public class MyWebSocketHandler implements  WebSocketHandler {


	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		log.info("connect websocket successful!");
		Object userId = session.getAttributes().get(WebSocketConstants.TOKEN);
		if(userId==null){
			return;
		}
		WebSocketSession oldSession = WebSocketCommon.CLIENT_SESSION.get(WebSocketCommon.getMapKey(session));
		if (oldSession != null) {
			log.info("close original session-start");
			try {
				oldSession.close();
			} catch (IOException e) {
				log.info("close original session failed");
			}
		}
		//新的会话放入
		WebSocketCommon.CLIENT_SESSION.put(WebSocketCommon.getMapKey(session),session);
	}

	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		log.info("handle message start");
		try {
			//String mess = (String) message.getPayload();  //获取客户端发送的消息
			//这边可能需要处理更新map里session机制，防止map里面保存的失效，待定，等后面实际运行观察
			if(session.isOpen()){
				//心跳响应包
				session.sendMessage(new PongMessage());
			}
		} catch (Exception e) {
			log.error("e", e);
		}
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		log.info("handle message start");
		if (session.isOpen()) {
			session.close();
		}
		log.error("connect error", exception);
		Object userid = session.getAttributes().get(WebSocketConstants.TOKEN).toString();
		if(userid==null){
			return;
		}
		WebSocketCommon.CLIENT_SESSION.remove(WebSocketCommon.getMapKey(session));
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		log.error("在线人数: {}" + WebSocketCommon.CLIENT_SESSION.size());
		log.error("connection closed: " + closeStatus);
		WebSocketCommon.CLIENT_SESSION.remove(WebSocketCommon.getMapKey(session));
		log.error("在线人数: {}" + WebSocketCommon.CLIENT_SESSION.size());
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}
}

